package com.atguigu.srb.core.service.impl;

import ch.qos.logback.classic.layout.TTLLLayout;
import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.BusinessAssert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.dto.ExcelDictDTO;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xmlconfig.impl.QnameconfigImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author 龙龙龙
 * @since 2022-01-21
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean importData(MultipartFile multipartFile) {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        //可以写文件的路径 也可以写流 一般开发用个读流的方式
        try {
            EasyExcel.read(multipartFile.getInputStream(), ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
            log.info("importData finished");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dicts = baseMapper.selectList(null);
        List<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
        for (Dict dict : dicts) {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();

            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOS.add(excelDictDTO);
        }
        return excelDictDTOS;
    }


    @Override
    public List<Dict> listByParentId(Long parentId) {
        //声明缓存集合
        List<Dict> dictList = null;

        //缓存建的命名规则： object：id：field
        // User:1:password   Good:2:info
        //先查缓存
        dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);

        //判断
        if (dictList != null) {

            return dictList;
        }

        //如果为空 查询db 再设置缓存
        dictList = listByNoCacheParentId(parentId);
        if (null != dictList) {
            //将db中的数据同步缓存
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList);
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        BusinessAssert.notNull(dict, ResponseEnum.ERROR);
        Long id = dict.getId();
        return this.listByParentId(id);
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);

        Long parentId = dict.getParentId();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId).eq("value",value);
        Dict one = baseMapper.selectOne(queryWrapper);
        return dict.getName();

    }

    public List<Dict> listByNoCacheParentId(Long parentId) {
        //条件构造器
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", parentId);

        //查询
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
            //判断当前dict是否有子集 有则把hasChildren改成true
            boolean b = hasChildren(dict.getId());
            if (b) {
                dict.setHasChildren(true);
            }
        }
        return dicts;
    }

    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count.intValue() > 0) {
            return true;
        }
        return false;
    }
}
